package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // 探店热门博文
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            //3.给isLike赋值
            isLiked(blog);
            //展示当前笔记作者信息
            queryBlogUser(blog);

        });
        return Result.ok(records);
    }

    //点赞功能
    @Override
    public Result likeBLog(Long id) {
        //获取用户userid
        Long userid = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //利用redis判断是否点赞过
        Double score = stringRedisTemplate.opsForZSet().score(key, userid.toString());
        //没点过赞修改点赞数量 改为sortedset
        //如果存在则返回分数，不存在则返回null
        if(score == null){ //用set时返回值是Boolean包装类所以要用BooleanUtil将其转换为基本类型防止空指针
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            //点赞成功保存用户到set集合
            if(update){
                stringRedisTemplate.opsForZSet().add(key, userid.toString(), System.currentTimeMillis());
            }

        }else {
            //已经点过赞再次点击
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2 把用户从Redis的set集合移除
            if(update){
                stringRedisTemplate.opsForZSet().remove(key,userid.toString());
            }

        }
        return Result.ok();
    }

    //查看探店笔记
    @Override
    public Result queryBlogById(Long id) {
        //1.根据id获取blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        //2.获取用户信息
        queryBlogUser(blog);
        //3.给isLike赋值
        isLiked(blog);

        return Result.ok(blog);
    }

    //点赞排行榜
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //获取top点赞
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(range == null || range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIds = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", userIds);
        //这里如果通过mp查询数据库会自动按照升序排列，而需要的是按照返回的顺序排列,所以last方法指定排序方案
        List<UserDTO> userDTOS = userService.query()
                .in("id", userIds).last("ORDER BY FIELD(id," + join + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    //笔记保存同时实现推送给粉丝收件箱功能
    //Feed流的滚动分页
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long followId = UserHolder.getUser().getId();
        //注意userid的字段属于blog当中相当于逻辑外键后续有用
        blog.setUserId(followId);
        // 保存探店博文
        boolean success = save(blog);
        if (!success) {
            return Result.fail("新增笔记失败！");
        }

        //查询当前用户和粉丝表
        List<Follow> follows = followService.query().eq("follow_user_id", followId).list();
        //遍历推送
        //如果 lambda 表达式的主体只有一行代码，可以省略大括号 {} 和 return 关键字
        follows.forEach(follow -> {
            //粉丝id
            Long userid = follow.getUserId();
            String key = FEED_KEY + userid;
            //推送被关注用户笔记的id到redis
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString()
            ,System.currentTimeMillis());
        });
        return Result.ok(blog.getId());
    }

    //好友关注-实现分页查询收邮箱
    @Override
    public Result queryBlogofFollow(Long max, Integer offset) {
        //1.最大值是上一次查询的最小值
        // 2.offset就是跳过的数量 第一次默认为0后续查询如果没有时间戳相等的的情况下默认为1，
        // 如果有相同时间戳的笔记则加上相同时间戳的数量，最大值是<=,重头查询如果有相同的时间戳就只会跳一个后面的再第二次仍然查出来了
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = FEED_KEY + userId;
        //2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        //reverseRangeByScoreWithScores作用是按照分数从大到小排序参数为key，最大值，最小值，偏移量，数量
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        // 4.解析数据：blogId、minTime（时间戳）、offset
        ArrayList<Long> ids = new ArrayList<>();
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取笔记id
            ids.add(Long.valueOf(Objects.requireNonNull(typedTuple.getValue())));
            //获取时间戳
            long time = Objects.requireNonNull(typedTuple.getScore()).longValue();
            //因为给的minTime这个
            //求得一次查询笔记末尾到底多少个相同的时间戳防止下一次查询重复的笔记
            //先查最新的往下走时间戳是递减的
            if(time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        // 5.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).
                last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs) {
            // 5.1.查询blog有关的用户
            queryBlogUser(blog);
            // 5.2.查询blog是否被点赞
            isLiked(blog);
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);

    }


    private void isLiked(Blog blog) {
        //获取用户
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = userDTO.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


}
